/**
 * Created by liuhe on 2016/12/16.
 */
'use strict';

//引入model
import ConfigOrderModel from '../dao/configOrder/config-order-model';
import { unzip } from '@qianmi/x-site-common/util/zlib-util';
import * as Immutable from 'immutable';
import { Client } from '@qianmi/x-site-common/util/oss';
import { constCommon } from '@qianmi/x-site-common/const-common';
let configOrderFilePath = constCommon.ossPath.pageConfigOrder;

interface ConfigOrderInterface {
  getConfigOrder(obj: any);
  upsertConfigOrder(obj: any);
  deleteConfigOrder(obj: any);
  getConfigOrdersList(obj: any);
}
export default class ConfigOrderService implements ConfigOrderInterface {
  ossClient: Client;

  constructor(ossClient: Client) {
    this.ossClient = ossClient;
  }
  /**
     * 查询获取 configOrder 数据库拿不到数据 就去 阿里云 拿  阿里云拿不到 就抛异常
     * @param env
     * @param uid
     * @param systemCode
     * @param platform
     * @param pageType
     * @param pageCode
     * @returns {Promise}
     */
  public async getConfigOrder({ env, uid, systemCode, platform, pageType, pageCode }) {
    let configOrder: any = await new Promise((resolve, reject) => {
      ConfigOrderModel.findOne({
        uid,
        systemCode,
        platform,
        pageType,
        pageCode
      })
        .lean()
        .exec(function(err, data: any) {
          data && data.configOrder ? resolve(data.configOrder) : err ? reject(err) : resolve(null);
        });
    });
    if (!configOrder) {
      //从阿里云获取文件
      let _configOrderFilePath = configOrderFilePath
        .replace('${env}', env)
        .replace('${systemCode}', systemCode)
        .replace('${userId}', uid)
        .replace('${platForm}', platform)
        .replace('${pageCode}', pageCode);
      try {
        let response = await this.ossClient.getObjectAbsolute(_configOrderFilePath);
        if (response.res.status === 200) {
          configOrder = await unzip(response.content.toString());
          configOrder = JSON.parse(configOrder);
        }
        //针对商品列表页面做 兼容处理
        if (pageType == 'goodsList') {
          configOrder = _cleanAjaxData(configOrder);
        }
        await this.upsertConfigOrder({
          uid,
          systemCode,
          platform,
          pageType,
          pageCode,
          configOrder
        });
      } catch (err) {
        //提供默认数据
        configOrder = null;
      }
    }
    return configOrder;
  }

  /**
     * 保存configOrder  有则改之 无则加之
     * @param uid
     * @param systemCode
     * @param platform
     * @param pageType
     * @param pageCode
     * @param configOrder
     * @returns {Promise}
     */
  public upsertConfigOrder({ uid, systemCode, platform, pageType, pageCode, configOrder }): Promise<any> {
    let target = { uid, systemCode, platform, pageType, pageCode };
    let result = { uid, systemCode, platform, pageType, pageCode, configOrder };
    return new Promise((resolve, reject) => {
      ConfigOrderModel.update(target, result, { upsert: true }).exec(function(err, data) {
        err ? reject(err) : resolve(data);
      });
    });
  }

  /**
     * 删除当前的configOrder
     * @param uid
     * @param systemCode
     * @param platform
     * @param pageType
     * @param pageCode
     * @returns {Promise}
     */
  public deleteConfigOrder({ uid, systemCode, platform, pageType, pageCode }): Promise<any> {
    return new Promise((resolve, reject) => {
      ConfigOrderModel.findOneAndRemove({ uid, systemCode, platform, pageType, pageCode }, (err, data) => {
        err ? reject(err) : resolve(data);
      });
    });
  }

  /**
     * 批量查找相关用户的所有configOrder的集合 提供给偷天换日使用 避免不停的查询用户的configOrder
     * @param uidArray      eg: ['A123','A234','A345','A456',...]
     * @param systemCode    eg: 'd2cStore'
     * @param platform
     * @param pageTypeArray eg: ['index','poster','goodsList']
     */
  public getConfigOrdersList({ uidArray, systemCode, platform, pageTypeArray }): Promise<any> {
    return new Promise((resolve, reject) => {
      ConfigOrderModel.find(
        {
          uid: { $in: uidArray },
          systemCode,
          platform,
          pageType: { $in: pageTypeArray }
        },
        {
          _id: 0,
          __v: 0
        }
      )
        .lean()
        .exec((err, data) => {
          err ? reject(err) : resolve(data);
        });
    });
  }
}

/**
 * 删除已经上传阿里云的configOrder中的桩数据
 * @param configOrder
 * @returns {*}
 */
function _cleanAjaxData(configOrder) {
  configOrder = Immutable.fromJS(configOrder);
  let __infoPath = [];
  treeConfig({
    configOrder,
    hitCompCalBack: (widgetConfig, pathArray) => {
      if (
        widgetConfig.get('widgetNameSpace') == 'x-site-ui-server/goods-list/condition-filter/mi/mi-goodsList-filter-bar'
      ) {
        __infoPath.push(pathArray.push('props').toJS());
      }
    }
  });
  for (let i = 0, len = __infoPath.length; i < len; i++) {
    configOrder = configOrder.deleteIn(__infoPath[i]);
  }
  return configOrder.toJS();
}

function treeConfig({ configOrder, hitCompCalBack, pathArray = Immutable.List() }) {
  hitCompCalBack && hitCompCalBack(configOrder, pathArray);
  if (!configOrder) {
    throw new Error(`对应路径配置为空::${pathArray.join(',')}`);
  }
  if (configOrder.has('children') && configOrder.get('children').count() > 0) {
    configOrder.get('children').forEach((subWidgetTreeConfig, index) => {
      return treeConfig({
        configOrder: subWidgetTreeConfig,
        hitCompCalBack,
        pathArray: pathArray.push('children').push(index)
      });
    });
  }
}
